package org.example;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.example.realm.CustomerMD5Realm;

import java.util.Arrays;

/**
 *
 */
public class TestCustomerMd5RealmAuthenticator {
    public static void main(String[] args) {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        // 设置realm使用hash凭证匹配器, 为了匹配md5加密之后的密码, 此时realm会帮你给输入加密之后再比较
        CustomerMD5Realm realm = new CustomerMD5Realm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024); // 设置散列次数
        realm.setCredentialsMatcher(credentialsMatcher);
        // 注入realm
        securityManager.setRealm(realm);
        // securityManager.setRealm(new CustomerMD5Realm());
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhourui", "123456");
        try {
            subject.login(token);
            System.out.println("认证状态: " + subject.isAuthenticated());
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        // 对已认证的用户进行授权
        if(subject.isAuthenticated()){
            // 基于但角色的权限控制
            System.out.println(subject.hasRole("admin"));
            // 基于多角色, 每个角色实际上会调用一次权限查询, 太多不好。
            System.out.println(subject.hasAllRoles(Arrays.asList("admin", "user")));
            // 基于多角色, 是否有其中一个, 返回的是一个boolean[], [true, true]这样。
            System.out.println(Arrays.toString(subject.hasRoles(Arrays.asList("admin", "user"))));

            System.out.println("**********基于权限字符串的访问控制**********");
            System.out.println(subject.isPermitted("user:update:01"));
            // 多资源 返回boolean[]
            System.out.println(Arrays.toString(subject.isPermitted("user:*:10", "user:create:01")));
            // 多资源 是否同时有
            System.out.println(subject.isPermittedAll("user:*:10", "user:create:01"));
        }
    }
}
